<!--
 * @Date: 2022-07-04 09:54:26
 * @LastEditTime: 2022-07-14 05:38:39
-->
<template>
  <div id="lg-panel-main-lg">
    <el-form :model="loginForm" :rules="login_rules" ref="loginForm" label-position="left" id="lg-panel-main-item">
      <el-form-item prop="username" class="lg-input-item-lg">
        <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item prop="password" class="lg-input-item-lg">
        <el-input v-model="loginForm.password" type="password" autocomplete="off" placeholder="请输入密码" @keypress.enter.native="login('loginForm')"></el-input>
      </el-form-item>
      <el-form-item class="lg-btn-item">
        <el-button @click="login('loginForm')" class="lg-button" type="primary">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { login } from '@/api/user'
export default {
  name: 'LoginPanel',
  data () {
    return {
      loginForm: {
        username: null,
        password: null
      },
      login_rules: {
        // TODO: 这个地方记得对照实际数据库的值
        username: [{required: true, message: '用户名不可为空', trigger: 'blur'}],
        password: [{required: true, message: '密码不可为空', trigger: 'blur'}]
      }
    }
  },
  methods: {
    login: function (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          login(this.loginForm)
            .then(res => {
              if (res.data.state === 200 && res.data.data.is_delete === 0) {
                this.$store.commit('updateUserInfo', res.data.data)
                // console.log(this.$store.state)
                this.$router.push('/')
                this.$message({
                  type: 'success',
                  message: '登录成功!'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: '用户名不存在或密码错误！'
                })
              }
            })
            .catch(err => {
              this.$message({
                type: 'error',
                message: err
              })
            })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style>
#lg-panel-main-lg {
  width: calc(100% - 20px);
  height: calc(100% - 110px);
  padding: 100px 10px 10px 10px;
}
.lg-input-item-lg {
  width: 80%;
  margin-bottom: 40px;
}
.lg-button {
  width: 100%;
}
.lg-btn-item {
  width: 80%;
  text-align: center;
}
</style>
